<?php

namespace Home;

use Home\Model\Album;
use Home\Model\AlbumTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Mine\Utils\TemplateHelper;

class Module {
	public function getAutoloaderConfig() {
		return array (
				'Zend\Loader\ClassMapAutoloader' => array (
						__DIR__ . '/autoload_classmap.php' 
				),
				'Zend\Loader\StandardAutoloader' => array (
						'namespaces' => array (
								__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__ 
						) 
				) 
		);
	}
	public function getConfig() {
		return include __DIR__ . '/config/module.config.php';
	}
	public function onBootstrap($e) {
		$e->getApplication ()->getEventManager ()->getSharedManager ()->attach ( 'Mine\Controllers\MyAbstractController', 'dispatch', function ($e) {
			$controller = $e->getTarget ();
			$controllerClass = get_class ( $controller );
			$moduleNamespace = substr ( $controllerClass, 0, strpos ( $controllerClass, '\\' ) );
			$config = $e->getApplication ()->getServiceManager ()->get ( 'config' );
			
			$routeMatch = $e->getRouteMatch ();
			$actionName = strtolower ( $routeMatch->getParam ( 'action', 'not-found' ) ); // get the action name

			$controllerName = strtolower ( $routeMatch->getParam ( 'controller', 'not-found' ) ); // get the action name
			
			if (isset ( $config ['module_layouts'] [$moduleNamespace] [$actionName] )) {
				$controller->layout ( $config ['module_layouts'] [$moduleNamespace] [$actionName] );
			} elseif (isset ( $config ['module_layouts'] [$moduleNamespace] ['default'] )) {
				$controller->layout ( $config ['module_layouts'] [$moduleNamespace] ['default'] );
			}
			$controller->layout ()->templateURL = TemplateHelper::getTemplateURL();
		}, 100 );
	}
	
	public function getServiceConfig() {
		return array (
				'factories' => array (
						'Home\Model\AlbumTable' => function ($sm) {
							$tableGateway = $sm->get ( 'AlbumTableGateway' );
							$table = new AlbumTable($tableGateway);
							return $table;
						},
						'AlbumTableGateway' => function ($sm) {
							$dbAdapter = $sm->get ( 'Zend\Db\Adapter\Adapter' );
							$resultSetPrototype = new ResultSet ();
							$resultSetPrototype->setArrayObjectPrototype ( new Album () );
							return new TableGateway ( 'album', $dbAdapter, null, $resultSetPrototype );
						} 
				) 
		);
	}
}
